﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using JM.JCY.Proxy;
using JM.JCY.BusinessEntity;
using NCS.IConnect.ApplicationContexts;
using JM.JCY.Common;
using System.IO;
using System.Globalization;
using System.Text;
using System.Data;
using System.Text.RegularExpressions;
using System.Web.UI.HtmlControls;
using System.Web.Services;
using System.Collections.Generic;
using Microsoft.SharePoint;



namespace JM.JCY.SharePointComponent.UserManagement.CreateDept
{
    public partial class CreateDeptUserControl : UserControl
    {
        static string JCYUrl = System.Configuration.ConfigurationManager.AppSettings["JCYUrl"].ToString();
        public string _userName
        {
            set { ViewState["_userName"] = value; }
            get { return (string)ViewState["_userName"]; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            _userName = ApplicationContext.Current.UserName;
            if (!IsPostBack)
            {
                box1View.DataSource = GetCodeTable(1, "JobTitle");
                box1View.DataTextField = "CodeDesc";
                box1View.DataValueField = "CodeVaule";
                box1View.DataBind();


            }

            if (!IsPostBack)
            {
                box1View.DataSource = GetCodeTable(1, "JobTitle");
                box1View.DataTextField = "CodeDesc";
                box1View.DataValueField = "CodeVaule";
                box1View.DataBind();
            }

        }


        protected void imgbtnSave_Click(object sender, ImageClickEventArgs e)
        {
            if (Page.IsValid)
            {
                SPWeb currentWeb = SPContext.Current.Web;
                string currentUserName = currentWeb.CurrentUser.Name.ToString();

                using (UserManagementProxy proxy = new UserManagementProxy())
                {
                    DataSetUserManagement dsUserMgr = new DataSetUserManagement();
                    DataSetUserManagement.T_DepartmentDataTable dtUserMgr = dsUserMgr.T_Department;
                    DataSetUserManagement.T_JobTitleDataTable dtJobTitle = dsUserMgr.T_JobTitle;
                    DataSetUserManagement.T_DepartmentRow drUserMgr = dtUserMgr.NewT_DepartmentRow();

                    string deptName = this.txtDeptName.Text.Trim();
                    string deptDesc = this.txtDeptDescription.InnerText;

                    drUserMgr.DeptName = deptName;
                    drUserMgr.DeptDesc = deptDesc;
                    drUserMgr.SortOrder = drUserMgr.ID;
                    drUserMgr.IsDeleted = false;
                    JCYUtility.UpdateCommonFields(drUserMgr, currentUserName);
                    dtUserMgr.Rows.Add(drUserMgr);


                    string s = Request.Form[box2View.UniqueID];
                    if (!string.IsNullOrEmpty(s))
                    {
                        foreach (var item in s.Split(','))
                        {
                            DataSetUserManagement.T_JobTitleRow drJobTitle = dtJobTitle.NewT_JobTitleRow();
                            drJobTitle.DeptId = drUserMgr.ID;
                            drJobTitle.JobTitle = item.ToString();
                            drJobTitle.IsDeleted = false;
                            JCYUtility.UpdateCommonFields(drJobTitle, currentUserName);
                            dtJobTitle.Rows.Add(drJobTitle);
                        }
                    }

                    CreateDocumentLibrary(deptName, deptDesc, SPListTemplateType.DocumentLibrary);
                    CreateDocumentLibrary(deptName + " 讨论版", deptDesc, SPListTemplateType.DiscussionBoard);
                    CreateDeptDesc(deptName);
                    proxy.CreateNewDepartment(dsUserMgr);
                }
                Response.Redirect("deptmgr.aspx");
            }
        }

        private void CreateDeptDesc(string deptName)
        {
           SPSecurity.RunWithElevatedPrivileges(delegate()
           {
               using (SPSite site = new SPSite(JCYUrl))
               {
                   using (SPWeb myWeb = site.AllWebs["MyDept"])
                   {

                       myWeb.AllowUnsafeUpdates = true;
                       SPList deptDesc = myWeb.Lists["部门文化风险综合表"];
                       SPListItem spItem = deptDesc.AddItem();
                       spItem["部门名称"] = deptName;
                       spItem["部门描述"] = "-";
                       spItem["部门文化"] = "-";
                       spItem["部门职责"] = "-";
                       spItem["主要廉政风险点"] = "-";
                       spItem["对应防控措施"] = "-";
                       spItem.Update();

                       myWeb.AllowUnsafeUpdates = false;
                   }
               }
           });
        }

        protected void imgbtnCancel_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("deptmgr.aspx");
        }

        public CodeTableDataSet.T_CodeTableDataTable GetCodeTable(int applicationId, string codeCategory)
        {
            CodeTableDataSet.T_CodeTableDataTable dt = new CodeTableDataSet.T_CodeTableDataTable();
            using (CodeTableProxy proxy = new CodeTableProxy())
            {
                dt = proxy.GetCodeTable(applicationId, codeCategory);
            }
            return dt;
        }

        private void CreateDocumentLibrary(string docName, string docDesc, SPListTemplateType templateType)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(JCYUrl))
                {
                    using (SPWeb myWeb = site.AllWebs["MyDept"])
                    {
                   
                        myWeb.AllowUnsafeUpdates = true;
                        myWeb.Lists.Add(docName, docDesc, templateType);
                        myWeb.Update();
                

                        // break permission from parent 
                        SPList newDoc = myWeb.Lists[docName];
                        if (!newDoc.HasUniqueRoleAssignments)
                            newDoc.BreakRoleInheritance(true);
                        SPRoleAssignmentCollection assignmentCol = newDoc.RoleAssignments;
                        for (int i = assignmentCol.Count - 1; i >= 0; i--)
                        {
                            assignmentCol.Remove(i);
                        }

                        // create group and set group owner
                        if (!IsExistGroup(docName))
                        {
                            SPUser owner = myWeb.EnsureUser(_userName);
                            myWeb.SiteGroups.Add(docName, owner, null, "Contributors to " + docName);
                        }

                        SPGroup newContribGroup = myWeb.SiteGroups[docName];
                        SPRoleDefinition contribRole = myWeb.RoleDefinitions.GetByType(SPRoleType.Contributor);
                        SPRoleAssignment contribRoleAssignment = new SPRoleAssignment(newContribGroup);
                        contribRoleAssignment.RoleDefinitionBindings.Add(contribRole);
                        newDoc.RoleAssignments.Add(contribRoleAssignment);
                        myWeb.AllowUnsafeUpdates = false;
                        myWeb.Dispose();
                        site.Dispose();
                    }
                }
                    
            });
         }

        public bool IsExistGroup(string groupname)
        {
            bool exist = false;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {

                using (SPSite site = new SPSite(JCYUrl))
                {
                    using (SPWeb web = site.AllWebs[JCYConstant.SiteName.MyDept])
                    {

                        SPGroupCollection groups = web.SiteGroups;
                        foreach (SPGroup grouplist in groups) //判断组是否存在
                        {
                            if (grouplist.ToString().ToLower() == groupname.ToLower())
                                exist = true;
                        }
                    }
                }
            });

            return exist;


        }

       

    }
}
